package com.test.base.nio1.readtest;

import com.test.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 设置非阻塞
        ssc.configureBlocking(false);
        // 2.绑定端口和主机（默认为127
        ssc.bind(new InetSocketAddress(8080));
        // 3.连接集合 -- 接受到的client连接
        List<SocketChannel> channels = new ArrayList<SocketChannel>();
        while (true) {
            //4. accpet：与客户端建立连接
//            log.debug("connecting...");
            SocketChannel sc = ssc.accept();

            if (sc != null) {
                sc.configureBlocking(false);
                log.debug("connected...{}", sc);
                channels.add(sc);
            }
            // 5. 遍历所有的连接
            for (SocketChannel channel : channels) {
//                log.debug("before read...{}", channel);
                // 从buffer中读取数据
                int read = channel.read(buffer);
                if (read > 0)
                {
                    buffer.flip();
                    ByteBufferUtil.debugAll(buffer);
                    buffer.clear();
                    log.debug("after read...{}", channel);
                }
            }
        }
    }
}
